package com.qunar.toku.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ProxyFactory {
	private static Map cache = new ConcurrentHashMap();

	public static <T> T create(Class type, String strUrl) {
		String key = strUrl;
        Object proxy = null;
        if (cache.containsKey(key)) {
            proxy = cache.get(key);
        }
        if (proxy == null) {
            proxy = createStandardProxy(strUrl, type);
            if (proxy != null) {
                cache.put(key, proxy);
            }
        }
        return (T)proxy;
	}

	private static Object createStandardProxy(String strUrl, Class<?> type) {
		String serviceName = "";
        String lookup = "";//接口实现类
        strUrl = strUrl.replace("tcp://", "");
        String[] splits = strUrl.split("/");
        if (splits.length == 2) {
        	serviceName = splits[0];
            lookup = splits[1];
        }
        
        InvocationHandler handler = new ProxyStandard(type, serviceName, lookup);
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{type},
                handler);
		
	}
}
